import React, { useState, useEffect } from 'react';
// 解析包
import { PdfLoader, PdfHighlighter, Tip, Highlight, Popup, AreaHighlight } from 'react-pdf-highlighter';
// 高亮测试数据
import { testHighlights as _testHighlights } from './test-highlights';
import { Spinner } from './Spinner';
import { Sidebar } from './Sidebar';
// 提示
import './style/App.css';

const testHighlights = _testHighlights;
//
const getNextId = () => String(Math.random()).slice(2);
const parseIdFromHash = () => document.location.hash.slice('#highlight-'.length);
const resetHash = () => {
  document.location.hash = '';
};
//
const HighlightPopup = ({ comment }) =>
  comment.text ? (
    <div className='Highlight__popup'>
      {comment.emoji} {comment.text}
    </div>
  ) : null;

// 文件地址
const PRIMARY_PDF_URL = 'https://arxiv.org/pdf/1708.08021.pdf';
// const PRIMARY_PDF_URL = "/2023.pdf";
const SECONDARY_PDF_URL = 'https://arxiv.org/pdf/1604.02480.pdf';
const searchParams = new URLSearchParams(document.location.search);
const initialUrl = searchParams.get('url') || PRIMARY_PDF_URL;

/**
 * PDF 编辑，此处需要React版本低于 18 以确保 class 组件能够使用
 * @returns
 */
export default function Index() {
  const [state, setState] = useState({
    url: initialUrl,
    highlights: testHighlights[initialUrl] ? [...testHighlights[initialUrl]] : []
  });
  // 初始化高度
  const resetHighlights = () => {
    setState({ ...state, highlights: [] });
  };
  // 给 document 设置url
  const toggleDocument = () => {
    const newUrl = state.url === PRIMARY_PDF_URL ? SECONDARY_PDF_URL : PRIMARY_PDF_URL;
    setState({
      url: newUrl,
      highlights: testHighlights[newUrl] ? [...testHighlights[newUrl]] : []
    });
  };
  //
  let scrollViewerTo = highlight => {};
  //
  const scrollToHighlightFromHash = () => {
    const highlight = getHighlightById(parseIdFromHash());
    if (highlight) {
      scrollViewerTo(highlight);
    }
  };
  //
  const getHighlightById = id => {
    const { highlights } = state;
    return highlights.find(highlight => highlight.id === id);
  };
  //
  const addHighlight = highlight => {
    const { highlights } = state;
    console.log('Saving highlight', highlight);
    setState({
      ...state,
      highlights: [{ ...highlight, id: getNextId() }, ...highlights]
    });
  };
  //
  const updateHighlight = (highlightId, position, content) => {
    console.log('Updating highlight', highlightId, position, content);
    setState({
      ...state,
      highlights: state.highlights.map(h => {
        const { id, position: originalPosition, content: originalContent, ...rest } = h;
        return id === highlightId
          ? {
              id,
              position: { ...originalPosition, ...position },
              content: { ...originalContent, ...content },
              ...rest
            }
          : h;
      })
    });
  };

  //
  useEffect(() => {
    window.addEventListener('hashchange', scrollToHighlightFromHash, false);
  }, []);

  return (
    <div className='PDFHightLighter' style={{ display: 'flex', height: '80vh' }}>
      {/* 左侧 注释 */}
      <Sidebar highlights={state.highlights} resetHighlights={resetHighlights} toggleDocument={toggleDocument} />
      <div
        style={{
          height: '80vh',
          width: '65vw',
          position: 'relative',
          border: '1px solid'
        }}
      >
        <PdfLoader url={state.url} beforeLoad={<Spinner />}>
          {pdfDocument => (
            <PdfHighlighter
              pdfDocument={pdfDocument}
              enableAreaSelection={event => event.altKey}
              onScrollChange={resetHash}
              pdfScaleValue='page-width'
              scrollRef={scrollTo => {
                scrollViewerTo = scrollTo;
                scrollToHighlightFromHash();
              }}
              onSelectionFinished={(position, content, hideTipAndSelection, transformSelection) => {
                console.log('是否执行此处！！！！', transformSelection);
                return (
                  <Tip
                    onOpen={transformSelection}
                    onConfirm={comment => {
                      addHighlight({ content, position, comment });

                      hideTipAndSelection();
                    }}
                  />
                );
              }}
              highlightTransform={(highlight, index, setTip, hideTip, viewportToScaled, screenshot, isScrolledTo) => {
                const isTextHighlight = !Boolean(highlight.content && highlight.content.image);

                const component = isTextHighlight ? (
                  <Highlight isScrolledTo={isScrolledTo} position={highlight.position} comment={highlight.comment} />
                ) : (
                  <AreaHighlight
                    isScrolledTo={isScrolledTo}
                    highlight={highlight}
                    onChange={boundingRect => {
                      updateHighlight(highlight.id, { boundingRect: viewportToScaled(boundingRect) }, { image: screenshot(boundingRect) });
                    }}
                  />
                );
                return (
                  <Popup
                    popupContent={<HighlightPopup {...highlight} />}
                    onMouseOver={popupContent => setTip(highlight, highlight => popupContent)}
                    onMouseOut={hideTip}
                    key={index}
                    children={component}
                  />
                );
              }}
              highlights={state.highlights}
            />
          )}
        </PdfLoader>
      </div>
    </div>
  );
}
